<?php
namespace App\Libraries\msg;

use App\Exceptions\ApiException;
use App\Jobs\SendPush;
use App\Models\ClientUser;
use App\Models\ClientUserMessage;
use JPush\Client;
use JPush\Exceptions\APIConnectionException;
use function Symfony\Component\VarDumper\Tests\Fixtures\bar;

class Push {
	protected $appkey;
	protected $secret;
	protected $client;
	
	public function __construct(){
	
	}
	
	/**
	 * @param $uid
	 * @param $title
	 * @param $content
	 * @param $extra
	 * @return bool
	 * 同步发送
	 */
	public function send($uid,$title,$content,array $extra = []){
		$status = $this->_send($uid,$title,$content,$extra);
		return $status;
	}
	
	/**
	 * @param $uid
	 * @param $title
	 * @param $content
	 * @param $extra
	 * @return bool
	 * 异步发送推送
	 */
	public function queue($uid,$title,$content,array $extra = []){
		$job = (new SendPush($uid,$title,$content,$extra))->onQueue('send_push');
		dispatch($job);
		return true;
	}
	
	public function _send(string $uid,string $title,string $content,array $extra){
		// 发送站内信
        $platform = $extra['platform'] ? $extra['platform'] : 'all';
		$sound = $extra['sound'] ?? '';

		$messages_type_id = $extra['messages_type_id'] ?? 1;
		$is_send = ($extra['is_send']>0)?1:0;
		unset($extra['messages_type_id']);
		unset($extra['platform']);

		if(!in_array($extra['type'],['rongcloud_complete','company_complaints_complete']) && $is_send){
			$messages_id = ClientUserMessage::send($uid,$title,$content,$messages_type_id);
		}

        if($sound && $platform =='all'){
            $extra['is_send'] = 0;
            $extra['platform'] = 'android';
            $extra['messages_id'] = $messages_id ?? 0;
            $this->queue($uid,$title,$content,$extra);
            $extra['platform'] = 'ios';
            $this->queue($uid,$title,$content,$extra);
            return true;
        }

        if(!$extra['messages_id']){
            $extras = ['type'=>'messages','messages_id'=>$messages_id ?? 0];
            $extras = array_merge($extras,$extra);
        }else{
            $extras = $extra;
        }

		// 判断是业主还是管家，是不同的秘钥
		$type = ClientUser::where(['id'=>$uid])->value('type');
		switch ($type){
			case 1 :
			case 3 :
				$this->appkey = '611658e4112ec0e6d4794f5c';
				$this->secret = '83639789b5b53fdd86a84300';
				break;
			case 2 :
				$this->appkey = 'fd9349337296579dd56ce666';
				$this->secret = 'c0ded20de140f8756911f8af';
				break;
			case 4:
				$this->appkey = '91fa17d2440ca9a4f4e4c32a';
				$this->secret = '97b17c72876afef9323346be';
				break;
			default :
				logger($uid.'不支持的用户类型，不推送');
				return true;
		}


		try{
            if($platform=='android'){
                $client = new Client($this->appkey,$this->secret,'./push.txt');
                $client->push()->setPlatform('android')->addTag($uid)->message($content, [
                    'title' => $title,
                    'extras' => $extras,
                ])->send();
            }else if($platform=='ios'){
                $client = new Client($this->appkey,$this->secret,'./push.txt');
                $client->push()->setPlatform('ios')->addTag($uid)->setNotificationAlert($title)
                    ->iosNotification($content,[
                        'badge'=>  '+1',
                        'sound'=>$sound,
                        'extras' => $extras,
                    ])->options([
                        'apns_production' => true
                    ])
                    ->send();
            }else{
                //如果没有声音，则一起推送
                $client = new Client($this->appkey,$this->secret,'./push.txt');
                $client->push()->setPlatform('all')->addTag($uid)->setNotificationAlert($title)
                    ->iosNotification($content,[
                        'badge'=>  '+1',
                        'sound'=>$sound,
                        'extras' => $extras,
                    ])->androidNotification($content,[
                        'badge'=>  '+1',
                        'extras' => $extras,
                    ])->options([
                        'apns_production' => true
                    ])
                    ->send();
            }
            unset($client);
		}catch(APIConnectionException $e){
			logger($uid.'推送失败，错误信息：'.$e->getMessage());
			return false;
		}
		return true;
	}

}